package com.lcy.demo;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 娄存银 on 2017/4/13.
 */
public class Demo {
    public static void main(String[] args) {
        String resource = "config.xml";
        InputStream inputStream = null;
        SqlSessionFactory sqlSessionFactory = null;
        SqlSession session = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(inputStream);
            session = sqlSessionFactory.openSession();

            // 通过 Mapper.xml 获取数据对象
            User user = session.selectOne("UserMapper.selectUser",1);
            System.out.println(user);

            // 通过注解接口获取数据对象
            PermissionMapper mapper = session.getMapper(PermissionMapper.class);
            Permission permission = mapper.selectPermission(1);
            System.out.println(permission);

            // 通过注解接口获取 HashMap 类型的数据
            HashMap<String,Object> map = mapper.selectMap(1);
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String format = "key : %s , value : %s ,value type : %s";
                String msg = String.format(format,entry.getKey(),entry.getValue(),entry.getValue().getClass().getName());
                System.out.println(msg);
            }

            // resultMap
            BaseBean userBean = session.selectOne("BeanMapper.selectUser",1);
            System.out.println(userBean);

            BaseBean permissionBean = session.selectOne("BeanMapper.selectPermission",1);
            System.out.println(permissionBean);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(inputStream != null) {
                    inputStream.close();
                }
                if(session != null){
                    session.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
